#include <QFile>
#include <QTextStream>
#include <QtDebug>
#include <QThread>
#include <QDateTime>

#include "file_data_division_processing.h"
#include "../data/constant_variables.h"

const QString File_data_division_processing::RECV_PROCESS_("sysRecv 1 process : ");
const QString File_data_division_processing::RECV_MESSAGE_("sysRecv 1 received message: ");

File_data_division_processing::File_data_division_processing(QObject *parent) : QObject(parent)
{
    init_connections();
}

File_data_division_processing::~File_data_division_processing()
{

}

void File_data_division_processing::init_connections()
{
    connect(this, &File_data_division_processing::sig_open_file,
            this, &File_data_division_processing::split_file_data_to_different_files);
}

void File_data_division_processing::split_file_data_to_different_files(QString file_name_with_path)
{
    QFile file(file_name_with_path);

    if ( file.open(QIODevice::ReadOnly)) {
        QTextStream in(&file);

        // 编码设置
        in.setCodec("UTF-8");
        QString content("");

        // 创建保存拆分数据的文件
        QFile out_file_process(file_name_with_path.replace(".log", "_PROCESS_.log",
                                                           Qt::CaseInsensitive));
        QFile out_file_received_message(file_name_with_path.replace("_PROCESS_.log", "_MESSAGE_.log",
                                                                    Qt::CaseInsensitive));

//        qDebug()<< "File_data_division_processing thread: " << (quint64) QThread::currentThreadId() << Qt::endl;

        // 两个文件以只写、前文清空模式打开
        if (out_file_process.open(QIODevice::WriteOnly | QIODevice::Truncate) &&
                out_file_received_message.open(QIODevice::WriteOnly | QIODevice::Truncate)) {

            QTextStream out_stream_process(&out_file_process);
            QTextStream out_stream_message(&out_file_received_message);

            // 按行读取数据，分别保存到2个文件中
            while (0 != (content = in.readLine()).length()) {
                if (content.contains("sysRecv 1 received message")) {
                    out_stream_message<< content.replace("sysRecv 1 received message", "") << Qt::endl;
                } else if (content.contains("sysRecv 1 process")) {
                    out_stream_process<< content.replace("sysRecv 1 process ", "") << Qt::endl;
                }
            }
        }
    }
}
